package microcredit.gui.action;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import microcredit.db.Factory;
import microcredit.gui.base.BaseAction;

public class ExportAction  extends BaseAction {
	
	private static final long serialVersionUID = 1L;
	
	private static final Log LOGGER = LogFactory.getLog(ExportAction.class);
	
	public ExportAction(Component parent) {
		super(parent);
		putValue(NAME, "<html>Export <font size='-4'>(CTRL + E)</font>");
		putValue(SMALL_ICON, new ImageIcon(AboutAction.class.getResource("/microcredit/icons/x16/server_mail_download.png")));
		putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.CTRL_DOWN_MASK));
	}
	
	@Override
	public void perform(ActionEvent e) throws Throwable {
		Component parent = JOptionPane.getFrameForComponent((Component)e.getSource());
		JFileChooser chooser = new JFileChooser(defaultFolder);
		chooser.addChoosableFileFilter(new FileFilter() {
			@Override
			public String getDescription() {
				return "Export ZIP file. (*.zip)";
			}
			
			@Override
			public boolean accept(File f) {
				if (f.isFile()) {
					return f.getName().toLowerCase().endsWith(".zip");
				}
				return true;
			}
		});
		int option = chooser.showSaveDialog(parent);
		if (option == JFileChooser.APPROVE_OPTION) {
			File f = chooser.getSelectedFile();
			
			if (!f.getName().toLowerCase().endsWith(".zip")) {
				f = new File(f.getParentFile(), f.getName()+".zip");
			}
			
			if (f.exists()) {
				String message = "The selected file does already exist.\n\nDo you want to overwrite it?";
				int confirmOption = JOptionPane.showConfirmDialog(parent, message);
				if (confirmOption != JOptionPane.YES_OPTION) {
					return;
				}
			}
			
			boolean ex = false;
			try {
				Factory.close(false);
				Factory.createImportExport().exportDatabase(f);
				defaultFolder = f.getParentFile();
			} catch (Exception e1) {
				ex = true;
				LOGGER.error(e1.getMessage(), e1);
				JOptionPane.showMessageDialog(parent, "An error occured while exporting the database: "+e1.getMessage(), "Error occured while exporting.", JOptionPane.ERROR_MESSAGE);
			} finally {
				Factory.open();
			}
			if (!ex) {
				JOptionPane.showMessageDialog(parent, "Database sucessfully exported to "+f.getAbsolutePath());
			}
		}
	}
	
}